package mine.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.orm.SugarRecord;
import com.whu.administrator.ws.MyApplication;
import com.whu.administrator.ws.R;
import com.whu.administrator.ws.UIHandler;

import java.text.SimpleDateFormat;
import java.util.Date;

import bbs.activity.BbsMainActivity;
import chat.network.tcp.PushControlReceiver;
import chat.network.tcp.PushService;
import mine.network.UserAttend;
import model.OwnUser;
import weibo.acitivity.BokeActivity;
import weibo.acitivity.SendWeiboActivity;

/**
 * 我的基本信息
 * Created by 凯 on 2015/11/12.
 */
public class MyActivity extends UIHandler.BaseActivity implements UserAttend.Delegate {

    // 返回按钮
    Button btn_back;

    // 帐号信息
    TextView tv_account;

    // 真实姓名
    TextView tv_realName;



    // 退出
    View v_logout;

    // 上班

    Button btn_shangban;

    // 下班
    Button btn_xiaban;
    LocationManager locationManager;
    AlertDialog alertDialog;
    Location location;
    //是否获取到位置
    boolean hasLocation;
    static Attend attend = new Attend();

    View v_jishiben;
    View v_beiwang;
    View v_rili;

    TextView tv_id;
    TextView tv_nickName;
    View v_weibo;

    public static Attend getAttend() {
        return attend;
    }

    public static void setAttend(Attend attend) {
        MyActivity.attend = attend;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        initview();
    }

    // 点击按钮
    View.OnClickListener itemClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == v_logout) {

                Intent intent = new Intent(MyActivity.this, PushControlReceiver.class);
                intent.putExtra(PushService.SERVICE_ACTION, PushService.ACTION_DESTORY);
                MyActivity.this.sendBroadcast(intent);

                // 退出所有界面
                UIHandler.uiHandler.finishiall();
                attend = null;

//                OwnUser ownUser = MyApplication.getOwnUser();
//                ownUser.setIsLogined(false);
//                SugarRecord.save(ownUser);
                SugarRecord.deleteAll(OwnUser.class);

            } else if (v == btn_back) {
                finish();
            }
            else if (v == btn_shangban) {
                openGpsListen();
                boolean gps = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
                if (!gps) {
                    Toast.makeText(MyActivity.this, "请打开网路定位开关！", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    // 当GPS定位时，在这里注册requestLocationUpdates监听就非常重要而且必要。没有这句话，定位不能成功。
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
                }
                alertDialog = new AlertDialog.Builder(MyActivity.this).setTitle("签到")
                        .setMessage("正在获取位置...，请稍等").setPositiveButton("签到", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (hasLocation) {

                                    UserAttend userAttend = new UserAttend();
                                    UserAttend.UserAttendance userAttendance = new UserAttend.UserAttendance();
                                    Date nowTime = new Date();
                                    SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    String timeStr = time.format(nowTime);
                                    userAttendance.setUser_ID(MyApplication.getOwnUser().getUser_ID());
                                    userAttend.setUserAttendance(userAttendance);
                                    userAttendance.setAttend_Longitude(location.getLongitude() + "");
                                    userAttendance.setAttend_Latitude(location.getLatitude() + "");
                                    userAttendance.setAttend_Time(timeStr);
                                    userAttendance.setAttend_Type(true);
                                    userAttend.setDelegate(MyActivity.this);
                                    // 签到
                                    userAttend.book();

                                } else {
                                    Toast.makeText(MyActivity.this, "尚未获取到位置信息", Toast.LENGTH_SHORT).show();
                                }
                                locationManager.removeUpdates(locationListener);
                                MyActivity.this.hasLocation = false;
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                locationManager.removeUpdates(locationListener);
                                MyActivity.this.hasLocation = false;
                                dialog.dismiss();
                            }
                        }).setCancelable(false).show();
            } else if (v == btn_xiaban) {
                openGpsListen();
                boolean gps = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
                if (!gps) {
                    Toast.makeText(MyActivity.this, "请打开网络定位开关！", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    // 当GPS定位时，在这里注册requestLocationUpdates监听就非常重要而且必要。没有这句话，定位不能成功。
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
                }
                alertDialog = new AlertDialog.Builder(MyActivity.this).setTitle("签到")
                        .setMessage("正在获取位置...，请稍等").setPositiveButton("签到", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (hasLocation) {

                                    UserAttend userAttend = new UserAttend();
                                    UserAttend.UserAttendance userAttendance = new UserAttend.UserAttendance();
                                    Date nowTime = new Date();
                                    SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    String timeStr = time.format(nowTime);
                                    userAttendance.setUser_ID(MyApplication.getOwnUser().getUser_ID());
                                    userAttend.setUserAttendance(userAttendance);
                                    userAttendance.setAttend_Longitude(location.getLongitude() + "");
                                    userAttendance.setAttend_Latitude(location.getLatitude() + "");
                                    userAttendance.setAttend_Time(timeStr);
                                    userAttendance.setAttend_Type(false);
                                    userAttend.setDelegate(MyActivity.this);
                                    // 签到
                                    userAttend.book();

                                } else {
                                    Toast.makeText(MyActivity.this, "尚未获取到位置信息", Toast.LENGTH_SHORT).show();
                                }
                                locationManager.removeUpdates(locationListener);
                                MyActivity.this.hasLocation = false;
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                locationManager.removeUpdates(locationListener);
                                MyActivity.this.hasLocation = false;
                                dialog.dismiss();
                            }
                        }).setCancelable(false).show();
            }
            else if (v == v_beiwang)
            {
                Intent intent = new Intent(MyActivity.this,BeiWangActivity.class);
                MyActivity.this.startActivity(intent);
            }
            else if (v == v_jishiben)
            {
                Intent intent = new Intent(MyActivity.this,NoteBookActivity.class);
                MyActivity.this.startActivity(intent);
            }
            else if (v == v_rili)
            {
                openRili();
            }
            else if (v == v_weibo)
            {
                Intent intent = new Intent(MyActivity.this, BbsMainActivity.class);
                MyActivity.this.startActivity(intent);
            }


        }
    };

    // 打开系统日历
    private void openRili() {
        try {
            Intent i = new Intent();
            ComponentName cn = null;
            if (Integer.parseInt(Build.VERSION.SDK) >= 8) {
                cn = new ComponentName("com.android.calendar",
                        "com.android.calendar.LaunchActivity");
            } else {
                cn = new ComponentName("com.google.android.calendar",
                        "com.android.calendar.LaunchActivity");
            }
            i.setComponent(cn);
            startActivity(i);
        } catch (ActivityNotFoundException e) {
            Log.e("ActivityNotFound", e.toString());
        }
    }

    // 启动获取GPS信息
    public void openGpsListen() {
        // 创建LocationManager对象
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // 判断是否打开GPS或者网络
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (!gps) {
            Dialog alertDialog = new AlertDialog.Builder(this).
                    setTitle("提高\"我的位置\"精确度").
                    setMessage("请打开网络定位开关").
                    setIcon(R.drawable.location_mark2).
                    setNeutralButton("设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(myIntent);
                        }
                    }).
                    setNegativeButton("取消", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }).
                    create();
            alertDialog.show();
        }


    }


    // 监听位置信息
    private LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            // 当GPS定位信息发生改变时，更新位置
            System.out.println("位置改变");
            MyActivity.this.location = location;

            alertDialog.setMessage("位置获取成功！");
            hasLocation = true;
            locationManager.removeUpdates(this);
        }

        @Override
        public void onProviderDisabled(String provider) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onStatusChanged(String provider, int status,
                                    Bundle extras) {
        }
    };

    // 初始化view
    private void initview() {
        btn_back = (Button) findViewById(R.id.id_btn_back);
        btn_back.setOnClickListener(itemClick);
        tv_account = (TextView) findViewById(R.id.id_tv_account);
        tv_realName = (TextView) findViewById(R.id.id_tv_realName);
        v_logout = findViewById(R.id.id_v_logout);
        v_logout.setOnClickListener(itemClick);

        btn_shangban = (Button) findViewById(R.id.id_btn_shangban);
        btn_shangban.setOnClickListener(itemClick);

        btn_xiaban = (Button) findViewById(R.id.id_btn_xiaban);
        btn_xiaban.setOnClickListener(itemClick);

        tv_id = (TextView) findViewById(R.id.id_tv_account);
        tv_id.setText(MyApplication.getOwnUser().getUser_ID());

        tv_nickName = (TextView) findViewById(R.id.id_tv_nickName);
        tv_nickName.setText(MyApplication.getOwnUser().getUser_NickName());

        tv_realName = (TextView) findViewById(R.id.id_tv_realName);
        tv_realName.setText(MyApplication.getOwnUser().getUser_RealName());

        v_jishiben = findViewById(R.id.id_v_jishiben);
        v_jishiben.setOnClickListener(itemClick);

        v_beiwang = findViewById(R.id.id_v_beiwang);
        v_beiwang.setOnClickListener(itemClick);

        v_rili = findViewById(R.id.id_v_rili);
        v_rili.setOnClickListener(itemClick);

        v_weibo = findViewById(R.id.id_v_weibo);
        v_weibo.setOnClickListener(itemClick);
    }


    @Override
    public void onResponse(String response, UserAttend userAttend) {
        if (userAttend.getResponseAttend().getStatus().equals(UserAttend.AttendStatus.SUCCESS)) {
            Toast.makeText(this, "签到成功", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onErrorResponse(VolleyError error, UserAttend userAttend) {
        Toast.makeText(this, "服务器错误", Toast.LENGTH_SHORT).show();
    }



    // 上次成功的签到时间
    public static class Attend {
        String date;
        boolean come;
        boolean leave;

        int status;

        public String getDate() {
            return date;
        }

        public void setDate(String date) {
            this.date = date;
        }

        public boolean getCome() {
            return come;
        }

        public void setCome(boolean come) {
            this.come = come;
        }

        public boolean getLeave() {
            return leave;
        }

        public void setLeave(boolean leave) {
            this.leave = leave;
        }

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }
    }
}
